<?php
/**
 * 
 * +------------------------------------------------------------+
 * @category Mssql 
 * +------------------------------------------------------------+
 * Mssql数据库驱动类，支持同时连接多个数据库
 * +------------------------------------------------------------+
 *
 * @author anzai <236049524@qq.com>
 * @copyright http://www.judianyun.com 2012
 * @version 1.0
 *
 * Modified at : 2012-02-16 10:57:21
 *
 */
class Mssql extends Db {
	public function close(){
		return $this->_links[$this->_linkID] && mssql_close($this->_links[$this->_linkID]);
	}
	
	public function connect($config='',$linkId=0){
		$this->_linkID = $linkId;
		try {
			if (!isset($this->_links[$linkId])){
				$config = empty($config) ? $this->_config[$linkId] : $config;
				$connect = true==$config['pconnect'] ? 'mssql_pconnect' : 'mssql_connect';
				$host = $config['dbhost'].($config['dbport']?":{$config['dbport']}":'');
				$this->_links[$linkId] = @$connect($host,$config['dbuser'], $config['dbpass']);
				if(!$this->_links[$linkId])
					throw new E(Helper::L('CLS_MSSSQLDB_LINK').' : '.$this->_error(),'db');
				if(empty($config['dbname']))
					throw new E(Helper::L('CLS_MSSQLDB_DBNAME'),'db');
				if(!mssql_select_db($config['dbname'],$this->_links[$linkId]))
					throw new E(sprintf(Helper::L('CLS_MYSQLDB_CONNECT_SELDB'),$config['dbhost'],$config['dbname']).' : '.$this->_error(),'db');
			}
		} catch (E $e) {
			$e->getMsg();
		}
		
		return $this;
	}
	
	public function count($sql=''){
 		$sql = empty($sql) ? 'SELECT COUNT(1) FROM '.$this->_table : $sql;
 		$result = $this->query($sql);
 		$count = mssql_result($result,0);
 		$this->free();
    	return $count;
    }
    
    public function exec($sql){
    	try{
    		parent::exec($sql);
    		$queryID = mssql_query($sql,$this->getLink());
	    	if (!$queryID) {
	    		throw new E(Helper::L('CLS_MYSQLDB_EXEC_SQL').' : '.$this->_querySql.'</b>','db');
	    	}
    		$this->_recordQuery();
    	}catch (E $e){
    		$e->getMsg();
    	}
    	
    	return $queryID;
    }
    
	public function getAll($sql,$result_type=MSSQL_ASSOC){
		$result = $this->query($sql);
		$data = array();
		while ($row = $this->_fetch_array($result,$result_type)) {
    		$data[] = $row;
    	}
    	$this->free();
    	return $data;
	}
	
	public function getFields($tableName=''){
		empty($tableName) && $tableName = $this->_table;
		$datas = $this->getAll("SELECT column_name,data_type,column_default FROM information_schema.tables AS t
        	JOIN information_schema.columns AS c ON t.table_catalog = c.table_catalog AND t.table_schema = c.table_schema
        	AND t.table_name = c.table_name WHERE t.table_name = '$tableName'");
		
		if (empty($datas)) return array();
		foreach ($datas as $field) {
			$fields[$field['column_name']] = array(
				'value' => $field['column_default'],
				'updated' => false
			);
		}
        return $fields;
	}
	
	public function getOne($sql,$result_type=MSSQL_ASSOC){
		return parent::getOne($sql,$result_type);
	}
	
	protected function free(){
		$res = true;
		if($this->_queryID){
			$res = mssql_free_result($this->_queryID);
        	$this->_queryID = 0;
		}
		return $res;
	}
	
	/**
	 * 重写插入数据的方法
	 * 
	 * @param string $fields 字段
	 * @param mixed $values 值，字符串或数组（表示插入多条）
	 * @param string $table 所操作的表
	 */
	public function insert($fields,$values,$table=null){
		try {
			if(empty($fields))
				throw new E(Helper::L('CLS_DB_INSERT_FIELD'),EXCEPTION_T_DB);
			if (empty($values))
				throw new E(Helper::L('CLS_DB_INSERT_VALUE'),EXCEPTION_T_DB);
			
			$table = $table === null  ? $this->_table : $table;
			if (is_array($values)){
				foreach ($values as $_v){
					$sql = 'INSERT INTO '.$table.'('.$fields.') VALUES('.$_v.')';
					if(!$this->exec($sql)){
						return false;
					}
				}
				return true;
			}else{
				$sql = 'INSERT INTO '.$table.'('.$fields.') VALUES('.$values.')';
				return $this->exec($sql);
			}
		}catch (E $e){
			$e->getMsg();
		}
	}
	
	public function lastInsertId(){
		if (!$this->_links[$this->_linkID]) 
			return 0;

        $result = $this->query('SELECT @@IDENTITY as last_insert_id');
        list($last_insert_id) = mssql_fetch_row($result);
        $this->free();
        return $last_insert_id;
	}
	
	private function _error() {
        return mssql_get_last_message();
    }
    
	protected function _fetch_array($result,$result_type=MYSQL_ASSOC){
    	return mssql_fetch_array($result,$result_type);
    }
}

?>